/*
 * init.cpp
 *
 *  Created on: 2014年10月27日
 *      Author: Administrator
 */

#include "init.hpp"
#include <bb/cascades/AbstractPane>
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/data/SqlDataAccess>
#include <bb/data/DataAccessError>
#include <bb/system/SystemDialog>
#include <bb/cascades/GroupDataModel>

#include <QtSql/QtSql>
#include <QDebug>
using namespace bb::cascades;
using namespace bb::data;
using namespace bb::system;

init::init()
{
}

QString init::dbFile(){
    return "./data/iFengNews.db";
};

void init::executeInit(){
    if(!QFile::exists(dbFile())){
        initDatabase();
        initFavoritesDatatable();
    }
}

QVariantMap init::initDatabase()
{
    QVariantMap result;
    result["statue"] = false;
    result["message"] = "Null";

    QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName(dbFile());

    if (database.open() == false) {
        const QSqlError error = database.lastError();
        result["statue"] = false;
        result["message"] = tr("Error opening connection to the database: %1").arg(error.text());
    }

    qDebug() << result["message"];

    return result;
}

QVariantMap init::initFavoritesDatatable(){
    qDebug() << "initFavoritesDatatable------------------";
    QVariantMap result;
    result["statue"] = false;
    result["message"] = "Null";

    SqlDataAccess *sqlda = new SqlDataAccess(dbFile());

    const QString createSQL =  "CREATE TABLE Favorites "
                                  "  (id INTEGER PRIMARY KEY AUTOINCREMENT, "
                                  "  title VARCHAR, "
                                  "  url VARCHAR, "
                                  "  content VARCHAR);";

    sqlda->execute(createSQL);
    if(!sqlda->hasError()) {
        result["statue"] = true;
        result["message"] = "Table created.";
    } else {
        const DataAccessError error = sqlda->error();

        result["statue"] = false;
        result["message"] = tr("Create table error: %1").arg(error.errorMessage());
    }

    qDebug() << result["message"];

    return result;
}

